package cn.edu.seu.herald.informationplatform.filter;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.seu.herald.informationplatform.bean.league.LeagueInfo;
import cn.edu.seu.herald.informationplatform.bean.league.LeagueUser;
import cn.edu.seu.herald.informationplatform.dao.cookie.CommonUserSessionCookieAccess;
import cn.edu.seu.herald.informationplatform.dao.cookie.SessionIdNotFound;
import cn.edu.seu.herald.informationplatform.dao.database.AttentionDao;
import cn.edu.seu.herald.informationplatform.dao.database.LeagueInfoDao;
import cn.edu.seu.herald.informationplatform.dao.database.LeagueUserDao;

public class LeagueInfoRequired implements Filter {

	public static final String LEAGUE_BEAN_NAME = "leagueBean";

	@Override
	public void init(FilterConfig config) throws ServletException {
	}

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request,
			ServletResponse response, FilterChain chain)
					throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		int leagueId = getLeagueId(httpRequest);
		
		try {
			LeagueUserDao leagueUserAccess = LeagueUserDao.getDao();
			LeagueUser league = leagueUserAccess.getLeagueUser(leagueId);
			int leagueInfoId = league.getLeagueInfoId();
			
			LeagueInfoDao leagueInfoAccess = LeagueInfoDao.getDao();
			LeagueInfo leagueInfo = leagueInfoAccess.getLeagueInfo(
					leagueInfoId);
			request.setAttribute(LEAGUE_BEAN_NAME, leagueInfo);
			
			buildAttention(httpRequest, leagueId);
		} catch (SQLException e) {
			httpResponse.sendError(404, "league info required");
			return;
		}
		
		chain.doFilter(request, response);
	}
	
	private int getLeagueId(HttpServletRequest httpRequest) {
		String leagueIdParam = httpRequest.getParameter(
				LeagueSpecified.PARAM_NAME_OF_LEAGUE_ID);
		return Integer.parseInt(leagueIdParam);
	}
	
	private void buildAttention(HttpServletRequest httpRequest, int leagueId)
			throws SQLException {
		try {
			CommonUserSessionCookieAccess coSessionCookieAccess =
					new CommonUserSessionCookieAccess(httpRequest);
			int userId = coSessionCookieAccess.getUserId();
			AttentionDao attentionDao = AttentionDao.getDao();
			
			if (attentionDao.contains(leagueId, userId)) {
				httpRequest.setAttribute("attention", true);
				return;
			}

			httpRequest.setAttribute("attention", false);
		} catch (SessionIdNotFound e) {
			httpRequest.setAttribute("attention", false);
		}
	}

}
